package com.bringway.framework.domain;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.NoSuchElementException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;

public class ResultSetIterator implements Iterator {
	private ResultSet rs;
	private final RowMapper rowMapper;
	private boolean hasNext = false;
	private long max=-1;
	private long count=0;
	
	public ResultSetIterator(ResultSet rs,RowMapper rowMapper){
		this.rs = rs;
		this.rowMapper = rowMapper;
	}
	
	public ResultSetIterator(ResultSet rs,long max,RowMapper rowMapper){
		this.rs = rs;
		this.rowMapper = rowMapper;
		this.max = max;
	}
	public boolean hasNext() {
		if (hasNext) {
            return true;
        }
		
		if (count>=max && max!=-1){
			hasNext = false;
			return hasNext;
		}

        try {
        	hasNext = rs.next();
        } catch (SQLException sqle) {
            return false;
        }
        
        return hasNext;
	}
	public Object next() {
		try {
			count++;
			if (count>=max && max!=-1){
				hasNext = false;
				throw new NoSuchElementException();
			}
			
            if (!hasNext) {
                hasNext = rs.next();
                if (!hasNext) {
                    throw new NoSuchElementException();
                }
            }
            // reset upon consumption
            hasNext = false;
            return rowMapper.mapRow(rs, rs.getRow());
        } catch (SQLException e) {
            NoSuchElementException xNoSuch = new NoSuchElementException("ResultSet exception: " + e);
            xNoSuch.initCause(e);
            throw xNoSuch;
        }
		
	}
	public void remove() {
		throw new UnsupportedOperationException("remove not supported");
	}
	public void release() {
		if (rs!=null){
			try{
				JdbcUtils.closeStatement(rs.getStatement());
				JdbcUtils.closeResultSet(rs);
			}catch (Exception e) {
			}
		}
	}
	
}
